define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util = require('util');
	var popwin = require('@base/dialog');
	var treeSelect = require('modules/treeSelect');

	// 溢价策略模块
	var ExtraPolicy = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'M-extraPolicy',
				'tplFile': '/tpl/campaign/modules/extraPolicy.html',
				'view_model': {
					'showGrid': false, // 显示表格
					'policys': [], // 策略数组
					'clickEdit': this.eventEidt, // 编辑一条策略
					'clickRemove': this.eventRemove // 删除一条策略
				}
			});
			this.$action = 'add'; // add, edit 标识添加还是编辑
			this.$index = -1; // 当前操作策略的序号
			this.$typeMap = { // 类型map
				'redirect': 1,
				'crowdProperty': 2,
				'schedule': 3,
				'pageClass': 5,
				'bdxCharacter': 6
			};
			this.$weekMap = { // 星期map
				'0': LANG('星期日'),
				'1': LANG('星期一'),
				'2': LANG('星期二'),
				'3': LANG('星期三'),
				'4': LANG('星期四'),
				'5': LANG('星期五'),
				'6': LANG('星期六')
			};
			this.$redReady = false; // 重定向模块是否创建完成
			this.$corReady = false; // 人群属性模块是否创建完成
			this.$bdxReady = false; // 其他人群模块是否创建完成
			this.Super('init', arguments);
		},
		afterBuild: function(){
			this.buildFromTemplate({
				'drop': {
					'def': LANG('新建策略'),
					'showResult': false,
					'width': 150,
					'options': [
							{ 'id': 'redirect', 'name': LANG('重定向') },
							{ 'id': 'crowdProperty', 'name': LANG('人群属性') },
							{ 'id': 'bdxCharacter', 'name': LANG('其他人群') },
							{ 'id': 'schedule', 'name': LANG('日程') }
					],
					'panel_config': {
						'hasSearch': false,
						'appendTo': 'popup'
					}
				},
				'tip': {
					'width': 260,
					'data': LANG('根据设定条件进行广告位溢价出价，对于同一条件设置多个溢价的，将会累加出价。')
				}
			});


			// 构建重定向
			this.create('popRedirect', PopRedirect);

			// 构建人群属性
			this.create('popCrowdProperty', treeSelect.popwin, {
				'showTitle': false,
				'key': 'BdxId',
				'param': {
					'url': 'category/people',
					'param': {
						'ChannelId': 10009
					}
				},
				'layout': {
					'module': '@base/dialog.base',
					'silence': false,
					'title': LANG('人群属性 - 包含以下条件')
				}

			});

			// 构建其他人群属性
			this.create('popBdxCharacter', treeSelect.popwin, {
				'showTitle': false,
				'param': {
					'url': 'PDMP/bdxPeople',
					'param': {
						'ChannelId': 168
					}
				},
				'layout': {
					'module': '@base/dialog.base',
					'silence': false,
					'title': LANG('其他人群 - 包含以下条件')
				}

			});

			// 构建日期
			this.create('popSchedule', PopSchedule);

			this.vm.watch('policys/length', function(){
				this.fire('policysChange');
			});
		},
		// 切换显示表格
		switchGridBox: function() {
			var vm = this.vm.$, len = vm['policys'].length;
			vm['showGrid'] = len === 0 ? false : true;
		},
		// 标识编辑状态
		signStatus: function( index ) {
			this.$action = index === -1 ? 'add' : 'edit';
			this.$index = index;
		},
		onDropChange: function(ev){
			var key = ev.param['id'] || ev.param['key'];
			switch( key ) {
				case 'redirect':
					this.addRedirect();
				break;
				case 'crowdProperty':
					this.addCrowdProperty();
				break;
				case 'schedule':
					this.addSchedule();
				break;
				case 'bdxCharacter':
					this.addBdxCharacter();
				break;
			}
			return false;
		},
		// 添加一条重定向
		addRedirect: function() {
			var popwin = this.$['popRedirect'];
			this.signStatus(-1);
			popwin.reset().show();
		},
		// 编辑一条重定向
		editRedirect: function( index ) {
			var policys = this.vm.getItem('policys');
			var sets = policys[index]['data']['ids'];
			this.signStatus(index);
			this.$.popRedirect.setValue(sets).show();
		},
		// 重定向选择后
		onRedirectSelected: function( ev ) {
			var vm = this.vm.$;
			var dataArr = ev.param, i = 0, len = dataArr.length;
			var nameArr = [], ids = [], content = LANG('包含：');
			for( ; i < len; i++ ) {
				nameArr.push( dataArr[i]['Name'] );
				ids.push( dataArr[i]['VisitorCateId'].toString() );
			}
			content += nameArr.join(', ');
			// 添加
			if( this.$action === 'add' ) {
				vm['policys'].push({
					'data': {
						'ids': ids,
						'all': _formatRedirectData(dataArr)
					},
					'type': 'redirect',
					'sort': LANG('重定向'),
					'content': content,
					'title': content,
					'price': 0
				});
			}
			// 编辑
			else if( this.$action === 'edit' && this.$index !== -1 ) {
				var now = vm['policys'][this.$index];
				now['data'] = {
					'ids': ids,
					'all': _formatRedirectData(dataArr)
				};
				now['content'] = content;
				now['title'] = content;
			}
			this.switchGridBox();
			this.$['popRedirect'].hide();
			return false;
		},
		// 添加一条人群属性
		addCrowdProperty: function() {
			var popwin = this.$['popCrowdProperty'];
			this.signStatus(-1);
			popwin
			.show()
			.load()
			.reset();
		},
		// 添加一条其他人群属性
		addBdxCharacter: function() {
			var popwin = this.$['popBdxCharacter'];
			this.signStatus(-1);
			popwin
			.show()
			.load()
			.reset();
		},
		// 编辑一条人群
		editCrowdProperty: function( index ) {
			var popwin = this.$['popCrowdProperty'];
			var policys = this.vm.getItem('policys');
			var sets = policys[index]['data'];
			this.signStatus( index );
			if( this.$corReady ) {
				this.setCrowdValue( sets );
			}
			else {
				popwin.load();
			}
		},
		// 编辑一条其他人群
		editBdxCharacter: function( index ) {
			var popwin = this.$['popBdxCharacter'];
			var policys = this.vm.getItem('policys');
			var sets = policys[index]['data'];
			this.signStatus( index );
			if( this.$bdxReady ) {
				this.setBdxCharacterValue( sets );
			}
			else {
				popwin.load();
			}
		},
		// 监听弹窗里的树数据加载完成
		onTreePopDataLoaded: function( ev ) {
			if(ev.name == 'popBdxCharacter'){
				this.$bdxReady = true;
				// 编辑状态下才setValue
				if( this.$action === 'edit' && this.$index !== -1 ) {
					var policys = this.vm.getItem('policys');
					var sets = policys[this.$index]['data'];
					this.setBdxCharacterValue( sets );
				}
			}else if(ev.name == 'popCrowdProperty'){
				this.$corReady = true;
				// 编辑状态下才setValue
				if( this.$action === 'edit' && this.$index !== -1 ) {
					var policys = this.vm.getItem('policys');
					var sets = policys[this.$index]['data'];
					this.setCrowdValue( sets );
				}
			}

			return false;
		},
		// 显示重定向的选中状态
		setCrowdValue: function( sets ) {
			var popwin = this.$['popCrowdProperty'];
			popwin
			.reset()
			.setValue( sets )
			.show();
		},
		setBdxCharacterValue: function( sets ) {
			sets = formatBdxCharacter(sets);
			var popwin = this.$['popBdxCharacter'];
			popwin
			.reset()
			.setValue( sets )
			.show();
		},
		// 人群选择后
		onTreeSelected: function( ev ) {
			var sort = '';
			var type = '';
			switch (ev.name){
				case 'popCrowdProperty':
					type = 'crowdProperty';
					sort = LANG('人群属性');
					break;
				case 'popBdxCharacter':
					type = 'bdxCharacter';
					sort = LANG('其他人群');
					break;
			}

			var vm = this.vm.$;
			var dataArr = ev.param, i = 0, len = dataArr.length;
			var nameArr = [], ids = [], content = LANG('包含：');
			for( ; i < len; i++ ) {
				nameArr.push( dataArr[i]['text'] );
				ids.push( dataArr[i]['id'].toString() );
			}
			content += nameArr.join(', ');
			// 添加
			if( this.$action === 'add' ) {
				vm['policys'].push({
					'data': dataArr,
					'type': type,
					'sort': sort,
					'content': content,
					'title': content,
					'price': 0
				});
			}
			// 编辑
			else if( this.$action === 'edit' && this.$index !== -1 ) {
				var now = vm['policys'][this.$index];
				now['data'] = dataArr;
				now['content'] = content;
				now['title'] = content;
			}
			this.switchGridBox();
			this.$['popCrowdProperty'].hide();
			this.$['popBdxCharacter'].hide();
			return false;
		},
		// 添加一条日程
		addSchedule: function() {
			var popwin = this.$['popSchedule'];
			this.signStatus(-1);
			popwin.reset().show();
		},
		// 编辑一条日程
		editSchedule: function( index ) {
			var popwin = this.$['popSchedule'];
			var vm = this.vm.$;
			this.signStatus( index );
			popwin
			.setValue( vm['policys'][index]['data'] )
			.show();
		},
		// 日程选择后
		onScheduleSelected: function( ev ) {
			var vm = this.vm.$;
			var date = ev.param;
			var html = '', detail = '', dayArr = [], i = 0;
			for( var pro in date ) {
				dayArr.push( this.$weekMap[pro] + '：' + _formatTime( date[pro] ) );
			}
			for( i = 0; i < dayArr.length; i++ ) {
				detail += dayArr[i] + '</br>';
			}
			html = [
				'<div class="timeIn">'+ LANG('包含：') +'</div>',
				'<div class="timeInCon">',
					detail || LANG('未选择') ,
				'</div>'
			].join('');
			// 添加
			if( this.$action === 'add' ) {
				vm['policys'].push({
					'data': date,
					'sort': LANG('日程'),
					'type': 'schedule',
					'content': html,
					'title': $(html).text(),
					'price': 0
				});
			}
			// 编辑
			else if( this.$action === 'edit' && this.$index !== -1 ) {
				var now = vm['policys'][this.$index];
				now['data'] = date;
				now['content'] = html;
				now['title'] = $(html).text();
			}
			this.switchGridBox();
			this.$['popSchedule'].hide();
			return false;
		},
		// 编辑策略
		eventEidt: function( type, index ) {
			switch( type ) {
				case 'redirect':
					this.editRedirect( index );
				break;
				case 'crowdProperty':
					this.editCrowdProperty( index );
				break;
				case 'bdxCharacter':
					this.editBdxCharacter( index );
				break;
				case 'schedule':
					this.editSchedule( index );
				break;
			}
		},
		// 删除一条策略
		eventRemove: function( index ) {
			this.vm.$['policys'].splice( index, 1 );
			this.switchGridBox();
		},
		getData: function() {
			var resArr = this.vm.getItem('policys'), retArr = [];
			var i = 0, len = resArr.length;
			for( ; i < len; i++ ) {
				var now = resArr[i];
				var data = now['data']; // 当前策略数据
				var type = now['type']; // 策略类型
				switch( type ) {
					case 'redirect': // 重定向
						//getData发送后端时，重定向cookie格式转化成id text
						var tmpData = formatCharacter(data['all']);
						retArr.push({
							'Character': tmpData,
							'CharacterValue': 0,
							'Stake': +now['price'],
							'Type': this.$typeMap[type]
						});
					break;
					case 'crowdProperty': // 人群属性
						retArr.push({
							'NPeople': _formatCrowdPropertyData( data ),
							'PeopleValue': 0,
							'Stake': +now['price'],
							'Type': this.$typeMap[type]
						});
					break;
					case 'schedule': // 日程
						retArr.push({
							'Schedule': data,
							'Stake': +now['price'],
							'Type': this.$typeMap[type]
						});
					break;
					case 'bdxCharacter': // 其他人群属性
						retArr.push({
							'BDXCharacter': formatBdxCharacter( data ),
							'BdxPeopleValue': 0,
							'Stake': +now['price'],
							'Type': this.$typeMap[type]
						});
					break;
					case 'pageClass': // 频道
						retArr.push({
							'PageClass': data,
							'Stake': +now['price'],
							'Type': this.$typeMap[type]
						});
					break;
				}
			}
			return retArr;
		},
		setData: function( data ) {
			var vm = this.vm.$;
			var i = 0, len = data.length, tmpArr = [];
			for( ; i < len; i++ ) {
				var now = data[i];
				var type = _getKeyName( now['Type'], this.$typeMap );
				var price = now['Stake'], j;
				var ids = [], nameArr = [], dataAll, content = LANG('包含：');
				switch( type ) {
					case 'redirect': // 重定向
						dataAll = now['Character'];
						for( j = 0; j < dataAll.length; j++ ) {
							nameArr.push( dataAll[j]['CateName'] );
							ids.push( dataAll[j]['VisitorCateId'].toString() );
						}
						content += nameArr.join(', ');
						tmpArr.push({
							'data': {
								'ids': ids,
								'all': dataAll
							},
							'type': type,
							'sort': LANG('重定向'),
							'content': content,
							'title': content,
							'price': price
						});
					break;
					case 'crowdProperty': // 人群属性
						dataAll = now['NPeople']['property'];
						for( j = 0; j < dataAll.length; j++ ) {
							nameArr.push( dataAll[j]['text'] );
							ids.push( dataAll[j]['id'].toString() );
						}
						content += nameArr.join(', ');
						tmpArr.push({
							'data': dataAll,
							'type': type,
							'sort': LANG('人群属性'),
							'content': content,
							'title': content,
							'price': price
						});
					break;
					case 'bdxCharacter': // 其他人群属性
						dataAll = now['BDXCharacter'];
						for( j = 0; j < dataAll.length; j++ ) {
							nameArr.push( dataAll[j]['CateName'] );
							ids.push( dataAll[j]['VisitorCateId'] );
						}
						content += nameArr.join(', ');
						tmpArr.push({
							'data': dataAll,
							'type': type,
							'sort': LANG('其他人群'),
							'content': content,
							'title': content,
							'price': price
						});
					break;
					case 'schedule': // 日程
						var date = now['Schedule'];
						var html = '', detail = '', dayArr = [];
						for( var pro in date ) {
							dayArr.push( this.$weekMap[pro] + '：' + _formatTime( date[pro] ) );
						}
						for( j = 0; j < dayArr.length; j++ ) {
							detail += dayArr[j] + '</br>';
						}
						html = [
							'<div class="timeIn">'+ LANG('包含：') +'</div>',
							'<div class="timeInCon">',
								detail || LANG('未选择') ,
							'</div>'
						].join('');
						tmpArr.push({
							'data': date,
							'sort': LANG('日程'),
							'type': type,
							'content': html,
							'title': $(html).text(),
							'price': price
						});
					break;
					case 'pageClass': // 频道
						dataAll = now['PageClass'];
						var html = '';
						var text = '';

						for( j = 0; j < dataAll.length; j++ ) {
							text += dataAll[j].id + LANG('（') + dataAll[j].name + LANG('）');
						}
						html = [
							'<div class="timeIn">'+ LANG('包含：') +'</div>',
							'<div class="timeInCon">',
								text || LANG('未选择') ,
							'</div>'
						].join('');
						tmpArr.push({
							'data': dataAll,
							'sort': LANG('频道'),
							'type': type,
							'content': html,
							'title': $(html).text(),
							'price': price
						});
					break;
				}
			}
			vm['policys'] = tmpArr;
			this.switchGridBox();
		},
		reset: function() {
			this.vm.reset();
			return this;
		}
	});
	exports.base = ExtraPolicy;

	// 重定向 弹窗内容
	var PopRedirect = popwin.base.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'title': LANG('重定向 - 根据cookies')
			});
			this.$dataReady = false;
			this.Super( 'init', arguments );
		},
		afterBuild:function(){
			this.Super( 'afterBuild', arguments );
			var el = this.getContainer();

			el.append([
				'<div pub-name="checkbox" pub-mod="@base/common/input.checkbox"/>'
			].join(''));

			this.buildFromTemplate({
				'checkbox': {
					'url': 'PDMP/list',
					'key': 'VisitorCateId',
					'name': 'Name',
					'reqType': 'websocket',
					'param': {
						'runstatus': 1 // 拉取状态为开启的重定向
					},
					'labelWidth': '20%',
					'labelHeight': '26',
					'hasSearch': true,
					'hasSelectAll': true,
					'hasInverse': true,
					'hasEmpty': true
				}
			});
		},
		onOk: function( ev ) {
			var data = this.$['checkbox'].getData('complete');
			this.fire( 'redirectSelected', data );
			this.hide();
			return false;
		},
		setValue: function( sets ) {
			this.$['checkbox'].setData( sets );
			return this;
		},
		reset: function() {
			this.$['checkbox'].reset();
			return this;
		}
	});
	exports.popRedirect = PopRedirect;

	// 日程 弹窗内容
	var PopSchedule = popwin.base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'title': LANG('日程')
			});
			this.Super( 'init', arguments );
		},
		afterBuild:function(){
			var self = this;
			self.Super( 'afterBuild', arguments );
			var el = self.getContainer();
			el.append('<div class="ml30" pub-mod="modules/timeZone.base" pub-name="schedule"/>');
			self.buildFromTemplate();
		},
		onOk: function(ev) {
			var data = this.$['schedule'].getData();
			this.fire( 'scheduleSelected', data );
			this.hide();
			return false;
		},
		setValue: function(value) {
			this.$['schedule'].setData(value);
			return this;
		},
		reset: function() {
			this.$['schedule'].reset();
			return this;
		}
	});
	exports.popSchedule = PopSchedule;

	// 日程表格时间格式化函数
	function _formatTime( data ) {
		data = data.slice();
		var first = data.shift(),
			text = first + '~',
			last = first + 1,
			list = [],
			now;
		for( var i = 0; i < data.length; i++ ) {
			now = data[i];
			if( now != last ) {
				text += last;
				list.push( text );
				text = now + '~';
			}
			last = now +1;
		}
		text += last;
		list.push( text );
		return list.join(', ');
	}

	// 重定向数据格式化函数（radioGroup中的字段转换为ExtraPolicy中的字段）
	function _formatRedirectData( data ) {
		var i = 0, len = data.length, ret = [];
		for( ; i < len; i++ ) {
			ret.push({
				'CateName': data[i]['Name'],
				'VisitorCateId': data[i]['VisitorCateId']
			});
		}
		return ret;
	}

	// 人群属性数据格式化函数
	function _formatCrowdPropertyData( data ) {
		var i = 0, len = data.length, proArr = [];
		for( ; i < len; i++ ) {
			proArr.push({
				'id': data[i]['id'],
				'text': data[i]['text']
			});
		}
		return {
			'property': proArr
			// 'sex': ["man", "woman"]
		};
	}

	// 获取对象键值名
	function _getKeyName( val, obj ) {
		var key = '';
		if( ( !val || !obj ) ) {
			return false;
		}
		for( key in obj ) {
			if( obj[key] == val ) {
				return key;
			}
		}
	}

	//getData发送后端时，重定向cookie格式转化{id:xx,text:xx}

	function formatCharacter(data){
		var result = [];
		util.each(data, function(item){
			result.push({
				'id': item.VisitorCateId,
				'text': item.CateName
			});
		});
		return result;
	}

	// 格式其他人群
	function formatBdxCharacter(data){
		var result = [];
		util.each(data, function(item){
			result.push({
				'id': item.VisitorCateId || item.id,
				'text': item.CateName || item.text
			});
		});
		return result;
	}
});